<style scoped>
#websiteEditorElem {
  height: 300px;
  background: #ffffff;
  margin-top: 0px;
  margin-left: 0px;
  display: table;
}
</style>
<template>
  <!-- 富文本编辑框 -->
  <div id="websiteEditorElem"></div>
</template>
 <script>
import E from "wangeditor";
export default {
  props: ["textData"],
  name: "weditor",
  data() {
    return {
      phoneEditor: "",
      name: "",
    };
  },
  methods: {
    // 给父组件返回富文本数据
    submit() {
      return this.phoneEditor.txt.html();
    },
    // 清除掉富文本内容
    clearhtml(){
      this.phoneEditor.txt.html("");
    },
    //   转base64
    filesToBase64(files) {
      const _this = this;
      files.map((item) => {
        var reader = new FileReader();
        reader.onload = function (e) {
          _this.uploadImg(e.target.result, item);
        };
        // 传入一个参数对象即可得到基于该参数对象的文本内容
        reader.readAsDataURL(item);
      });
    },

    // base64转blob
    Base64toBlob({ base64, success }) {
      var arr = base64.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const blob = new Blob([u8arr], { type: mime });
      success(blob);
    },

    // 上传图片
    uploadImg(base64, file) {
      const _this = this;
      const formData = new FormData();
      this.Base64toBlob({
        base64,
        success(blob) {
          formData.append("file", blob, file.name);
          formData.append("open", true);
          // 调用axios上传
          const config = {
            headers: { "Content-Type": "multipart/form-data" },
          };
          _this
            .$axios({
              method: "post",
              url: "/Index/uploads",
              headers: {
                "Content-Type": "multipart/form-data",
              },
              data: formData,
            })
            .then((res) => {
              // 根据自己的后台逻辑进行判断
              if (res.data.code === 0) {
                _this.$message.success("图片上传成功！");
                // 上传图片，返回结果，将图片插入到编辑器中
                let imgUrl = res.data.data.url;
                _this.phoneEditor.cmd.do(
                  "insertHtml",
                  '<img src="' + imgUrl + '" style="max-width:100%;"/>'
                );
              } else {
                _this.$message({
                  message: "文件服务异常，请联系管理员！",
                  type: "error",
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        },
      });
    },
  },

  mounted() {
    const me = this;
    this.phoneEditor = new E("#websiteEditorElem");
    this.phoneEditor.config.zIndex = 100;
    // 上传图片到服务器，base64形式
    this.phoneEditor.config.uploadImgShowBase64 = true;
    // 隐藏网络图片
    this.phoneEditor.config.showLinkImg = false;
    // 自定义上传图片
    this.phoneEditor.config.customUploadImg = function (
      resultFiles,
      insertImgFn
    ) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      me.filesToBase64(resultFiles);
    };
    // 创建一个富文本编辑器
    this.phoneEditor.create();
    // 富文本内容
    this.phoneEditor.txt.html(this.textData);
    if(this.textData!=="") {
      document.getElementsByClassName("placeholder")[0].innerHTML ="";
    }
  },
};
</script>